#    Copyright 2014 COOPGIS Consulting
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject import settings
from djangoproject.models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings

def GetGPSPoint(FileName):
    import csv
    if(djangoproject.settings.COOPGISServerIndicator):
        return None, 'No NMEA'
    if(os.path.exists(FileName)):
        try:   #If the file cannot be deleted, do not return a point [to minimize risk of pulling in points from old files]
            os.remove(FileName)
        except:
            return None, 'FileDeleteError'
    if(djangoproject.settings.COOPGISInVirtualMachineIndicator):
        os.system("sudo chmod 777 " + FTPFileName)
        if(os.path.exists(FTPFileName)):
            os.remove(FTPFileName)
        time.sleep(4) #Script on Host Machine will save out the file every 2 seconds, so this should ensure a good file if timings are correct on the Virtual Machine
        if(os.path.exists(FTPFileName)):
            os.system("sudo chmod 777 " + FTPFileName)
            shutil.copy(FTPFileName,FileName) 
    else: #Otherwise, get the point using the GPS scripts
        os.system("sudo su apachescript sudo -c 'python /opt/coopgis/scripts/GetGPSPoint.py'")
    try:    
        File=open(FileName, "r")
        CSV=csv.reader(File)
        for row in CSV:
            Longitude=float(row[0])
            Latitude=float(row[1])
            Quality=row[2]
            NewPoint=Point(x=Longitude, y=Latitude, srid=djangoproject.settings.COOPGISGPSSRID)
            NewPoint.transform(djangoproject.settings.COOPGISSRID)
            X=NewPoint.x
            Y=NewPoint.y
    except:
        pass
    try:
        File.close()
    except:
        pass
    try:
        if(X or Y) and not 'No Reading' in str(Quality):
            return Point(x=X, y=Y, srid=djangoproject.settings.COOPGISSRID), Quality
        else:
            return None, Quality
    except:   #return None, 'NO NMEA' was all that needed to be here, did a C&P of all above code for a quick way to not connect to BT on every get point attempt         
              #FIXME, refactor into functions...
        if(djangoproject.settings.COOPGISInVirtualMachineIndicator):
            return None, 'No NMEA'

        os.system("sudo su apachescript -c '/bin/bash /opt/coopgis/scripts/ConnectToBluetooth'")
        os.system("sudo su apachescript -c 'sudo python /opt/coopgis/scripts/GetGPSPoint.py'")

        try:    
            File=open(FileName, "r")
            CSV=csv.reader(File)
            for row in CSV:
                Longitude=float(row[0])
                Latitude=float(row[1])
                Quality=row[2]
                NewPoint=Point(x=Longitude, y=Latitude, srid=djangoproject.settings.COOPGISGPSSRID)
                NewPoint.transform(djangoproject.settings.COOPGISSRID)
                X=NewPoint.x
                Y=NewPoint.y
        except:
            pass
        try:
            File.close()
        except:
            pass
        try:
            if(X or Y) and not 'No Reading' in str(Quality):
                return Point(x=X, y=Y, srid=djangoproject.settings.COOPGISSRID), Quality
            else:
                return None, Quality
        except:
            return None, 'No NMEA'

def GetNearbyPoleFromGPS():
    GPSPoint, Quality=GetGPSPoint(djangoproject.settings.COOPGISGPSFileName)
    if(not GPSPoint):
        return None, Quality
    CurrentDistance=1 * djangoproject.settings.COOPGISDistanceMultiplier
    MaximumDistance=5280 * djangoproject.settings.COOPGISDistanceMultiplier #1 mile
    Step = 5 * djangoproject.settings.COOPGISDistanceMultiplier
    while(CurrentDistance<MaximumDistance):
        Stations=Station.objects.filter(Point__distance_lte=(GPSPoint, CurrentDistance))
        for i in Stations:
            Temp = Assembly.objects.filter(Station=i, CompatibleUnit__PoleIndicator=True)
            if(Temp):
                return Temp[0], Quality
        CurrentDistance=CurrentDistance+Step
        Step = Step + CurrentDistance / 5 #Get less specific the further away the pole is
    return None, Quality

def GetNearbyStationFromGPS():
    GPSPoint, Quality=GetGPSPoint(djangoproject.settings.COOPGISGPSFileName)
    if(not GPSPoint):
        return None, Quality
    CurrentDistance=1 * djangoproject.settings.COOPGISDistanceMultiplier
    MaximumDistance=5280 * djangoproject.settings.COOPGISDistanceMultiplier#1 mile
    Step = 5 * djangoproject.settings.COOPGISDistanceMultiplier
    while(CurrentDistance<MaximumDistance):
        Stations=Station.objects.filter(Point__distance_lte=(GPSPoint, CurrentDistance))
        for i in Stations:
            return i, Quality
        CurrentDistance=CurrentDistance+Step
        Step = Step + CurrentDistance / 5 #Get less specific the further away the station is
    return None, Quality

def GetNearbyStationandSpanFromGPS():
    GPSPoint, Quality=GetGPSPoint(djangoproject.settings.COOPGISGPSFileName)
    if(not GPSPoint):
        return None, None, Quality
    CurrentDistance=1 * djangoproject.settings.COOPGISDistanceMultiplier
    MaximumDistance=5280 * djangoproject.settings.COOPGISDistanceMultiplier #1 mile
    Step=5 * djangoproject.settings.COOPGISDistanceMultiplier
    span=None
    while(CurrentDistance < MaximumDistance):
        Spans=Span.objects.filter(Line__distance_lte=(GPSPoint, CurrentDistance))
        if(Spans):
            span=Spans[0]
            break
        Step = Step + CurrentDistance / 5 #Get less specific the further away the station is
        CurrentDistance=CurrentDistance+Step
    Step=5 * djangoproject.settings.COOPGISDistanceMultiplier
    while(CurrentDistance < MaximumDistance):
        Stations=Station.objects.filter(Point__distance_lte=(GPSPoint, CurrentDistance))
        for i in Stations:
            return i, span, Quality
        Step = Step + CurrentDistance / 5 #Get less specific the further away the station is
        CurrentDistance=CurrentDistance+Step
    return None, Quality


